<template>
	<view class="container">
		<view class="status_bar">
			<view style="margin-left: 4%;" @tap="goBack()"><u-icon name="arrow-leftward" size='24' /></view>
			<view style="font-weight: bold;"></view>
			<view style="display: flex;margin-right: 20upx;">

			</view>
		</view>
		<view class="status_bar"></view>
		<!-- <view class="head flex-row">
			<view class="title">登录</view>
		</view> -->
		<view class="logo-wrap">
			<image src="../static/image/logo.png" mode=""></image>
		</view>

		<!-- 	<view class="input-wrap">
			<u--input class="input" placeholder="请输入账号" prefixIcon="account"
				prefixIconStyle="font-size: 26px;color: #909399" v-model="form.nickName" type="text" border="none"
				placeholderStyle="color:#9d9ea0"></u--input>
		</view>
		<view style="margin-top: 24upx;margin-left: 14%;">
			<view style="color: #7ead8b; font-weight: 300; font-size: 28upx;">账号必须带有字母，长度4-16位</view>
		</view> -->
		<view class="input-wrap1">
			<u--input class="input" v-model="form.user_mail" placeholder="请输入注册邮箱" prefixIcon="email"
				:prefixIconStyle="iconStyle" border="none" :placeholderStyle="placeholderStyle" @input="validateEmail"
				@blur="validateEmail" />
			<p v-if="emailError" style="color: red; font-size: 12px;margin-left: 87px;">{{ emailError }}</p>
		</view>
		<view class="input-wrap" v-if="userId==2">
			<u--input class="input" placeholder="请输入昵称" prefixIcon="account"
				prefixIconStyle="font-size: 26px;color: #909399" v-model="form.nickName" type="text" border="none"
				placeholderStyle="color:#9d9ea0"></u--input>
		</view>
		<view class="input-wrap1" v-if="userId==2">
			<u--input class="input" placeholder="请输入密码" prefixIcon="lock"
				prefixIconStyle="font-size: 26px;color: #909399" :password="passwordShow" v-model="form.user_psw"
				border="none" placeholderStyle="color:#9d9ea0"></u--input>
			<image v-if="eyeShow==true" src="../static/image/icon-eye@3x.png" class="eye" @tap="oneye()">
			</image>
			<image v-else src="../static/image/icon-eye-o@3x.png" class="eye-o" @tap="oneyeOpen()"></image>
		</view>
		<!-- 	<view class="input-wrap1" v-if="userId==2">
			<u--input class="input" placeholder="确认密码" prefixIcon="lock"
				prefixIconStyle="font-size: 26px;color: #909399" :password="passwordShow" v-model="form.user_psw"
				border="none" placeholderStyle="color:#9d9ea0"></u--input>
			<image v-if="eyeShow==true" src="../static/image/icon-eye@3x.png" class="eye" @tap="oneye()">
			</image>
			<image v-else src="../static/image/icon-eye-o@3x.png" class="eye-o" @tap="oneyeOpen()"></image>
		</view> -->
		<!-- <view class="names">密保选择</view> -->

		<!-- 	<view class="input-wrap" style="width: 75%;background-color: #ffffff;margin: 0 auto;border: none;">
			<uni-data-select v-model="value" :localdata="range" @change="change" label="密保选择"></uni-data-select>
		</view> -->
		<!-- 	<view class="input-wrap" style="margin-top: 10px;">
			<u--input class="input" placeholder="请输入你的密保问题" prefixIconStyle="font-size: 26px;color: #909399"
				v-model="problem_desc" type="text" border="none" placeholderStyle="color:#9d9ea0"></u--input>
		</view> -->
		<!-- 	<view v-if="userId==1" class="input-wrap" style="margin-top: 10px;">
			<u--input class="input" placeholder="请输入你的新密码" prefixIconStyle="font-size: 26px;color: #909399"
				v-model="newpassword" type="text" border="none" placeholderStyle="color:#9d9ea0"></u--input>
		</view> -->
		<view v-if="userId==2" style="width: 70%;
					display: flex;
					justify-content: start;
					align-items: center;
					margin: 0 auto;">
			<!-- <canvas canvas-id="captchaCanvas" style="width: 150px; height: 50px; background-color: #f5f5f5;"></canvas> -->
			<!-- <input style="margin-left: 20px;" type="text" placeholder="请输入验证码" v-model="userInput" /> -->
		</view>

		<view style="margin-top: 24upx;margin-left: 14%;">
		</view>

		<view v-if="userId==1" class="login" :class="{able: isAbled}" @tap="logins">发送邮件</view>
		<view v-if="userId==2" class="login" :class="{able: isAbled}" @tap="login">注册</view>
		<view style="font-size: 12px;text-align: center;margin-top: 20px;display: flex;justify-content: center;">
			<span>
				<u-checkbox-group v-model="agree">
					<u-checkbox class="checkbox"></u-checkbox>
				</u-checkbox-group>
			</span>
			已阅读并同意<span style="color: blue;" @tap="gopage1()">应用程序协议</span>和<span style="color: blue;"
				@tap="gopage()">信息保护政策</span>
		</view>

		<!-- <view class="tip">
			<view class="item">客户端为DEMO(非商业用途)，如有侵权，请及时联系我们</view>
			<view class="item">反馈地址：<text class="link" @tap="toPage('/pages/web')">点击访问</text></view>
		</view> -->
	</view>
</template>

<script>
	export default {
		data() {
			return {
				form: {
					telephone: '',
					password: '',
					user_mail: '',
					user_sex: ''
				},
				emailError: '', // 错误提示
				newpassword: '',
				problem_type: 1,
				agree: [], // 使用数组存储选中的值（u-checkbox-group 默认格式）
				problem_desc: '',
				value: 1, // 默认选中 range 的第一个值
				range: [{
						value: 1,
						text: "你的出生年月？"
					},
					{
						value: 2,
						text: "你的小学名字？"
					}
				],
				captcha: '', // 当前验证码内容
				userInput: '', // 用户输入的内容
				eyeShow: true,
				passwordShow: true,
				eyeShow1: true,
				passwordShow1: true,
			}
		},
		computed: {
			isAbled() {
				return !this.$validate.isNull(this.form.telephone) && !this.$validate.isNull(this.form.password)
			}
		},
		mounted() {
			this.generateCaptcha(); // 页面加载时生成验证码
		},
		onShow() {
			uni.clearStorageSync()
			if (this.range.length > 0) {
				this.value = this.range[0].value; // 设置默认值为 range 的第一个选项
			}
		},
		onLoad(options) {
			if (options.id) {
				this.userId = options.id; // 获取传递过来的 id
				console.log('接收到的 id:', this.userId);
			}

		},

		methods: {
			validateEmail() {
				const emailPattern =
					/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; // 邮箱正则
				if (!this.form.user_mail) {
					this.emailError = '邮箱不能为空'; // 输入为空时提示
				} else if (!emailPattern.test(this.form.user_mail)) {
					this.emailError = '请输入有效的邮箱地址'; // 格式不符提示
				} else {
					this.emailError = ''; // 格式正确时清除提示
				}
			},
			generateCaptcha() {
				console.log('Generating captcha...');
				const canvas = uni.createCanvasContext('captchaCanvas');
				const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
				let captchaText = '';
				for (let i = 0; i < 5; i++) {
					captchaText += chars[Math.floor(Math.random() * chars.length)];
				}
				this.captcha = captchaText;

				// 清除画布
				canvas.clearRect(0, 0, 150, 50);

				// 绘制背景
				canvas.setFillStyle('#ffffff');
				canvas.fillRect(0, 0, 150, 50);

				// 绘制验证码字符
				for (let i = 0; i < captchaText.length; i++) {
					const x = 10 + i * 25;
					const y = 30 + Math.random() * 10;
					const fontSize = 20 + Math.random() * 5;
					const angle = (Math.random() - 0.5) * 30;

					canvas.setFontSize(fontSize);
					canvas.setFillStyle(this.randomColor());
					canvas.save();
					canvas.translate(x, y);
					canvas.rotate((angle * Math.PI) / 180);
					canvas.fillText(captchaText[i], 0, 0);
					canvas.restore();
				}

				// 添加干扰线
				for (let i = 0; i < 5; i++) {
					canvas.setStrokeStyle(this.randomColor());
					canvas.beginPath();
					canvas.moveTo(Math.random() * 150, Math.random() * 50);
					canvas.lineTo(Math.random() * 150, Math.random() * 50);
					canvas.stroke();
				}

				// 添加干扰点
				for (let i = 0; i < 30; i++) {
					canvas.setFillStyle(this.randomColor());
					canvas.fillRect(Math.random() * 150, Math.random() * 50, 2, 2);
				}

				canvas.draw();
			},
			// 生成随机颜色
			randomColor() {
				const r = Math.floor(Math.random() * 256);
				const g = Math.floor(Math.random() * 256);
				const b = Math.floor(Math.random() * 256);
				return `rgb(${r}, ${g}, ${b})`;
			},
			// 验证验证码
			validateCaptcha() {
				if (this.userInput.toLowerCase() === this.captcha.toLowerCase()) {
					uni.showToast({
						title: '验证成功',
						icon: 'success'
					});
				} else {
					uni.showToast({
						title: '验证码错误',
						icon: 'error'
					});
					this.generateCaptcha(); // 重新生成验证码
				}
			},
			change(e) {
				this.problem_type = e
			},
			goBack() {
				uni.navigateBack({
					delta: 1
				});
			},
			// 密保验证
			// logins() {
			// 	uni.request({
			// 		url: this.$api.baseUrl + '/api/common/pass_prote/get',
			// 		header: {
			// 			'content-type': 'application/json'
			// 		},
			// 		data: {
			// 			user_id: userId,
			// 			problem_type: this.problem_type,
			// 			problem_desc: this.problem_desc
			// 		},
			// 		method: 'POST',
			// 		success: res => {
			// 			this.toPage('/pages/login')
			// 		},
			// 		fail: res => {
			// 			console.log(res);
			// 		}

			// 	})
			// },

			// 修改密码
			logins() {
				uni.request({
					url: this.$api.baseUrl + '/api/user/problem/password',
					header: {
						'content-type': 'application/json'
					},
					data: {
						user_mail: this.form.user_mail,
						problem_type: this.problem_type,
						problem_desc: this.problem_desc,
						password: this.newpassword
					},
					method: 'POST',
					success: res => {
						this.$util.toast(res.data.message)
						if (res.data.code == 0) {
							this.$util.toast('修改成功')
							this.toPage('/pages/login')
						}

					},
					fail: res => {
						console.log(res);
					}

				})
			},
			// 假设在$validate对象所在的地方添加此方法（具体根据项目实际的验证模块组织情况调整）
			isValidNickName(nickName) {
				const reg = /^(?=.*[a-zA-Z]).{4,16}$/;
				if (reg.test(nickName)) {
					return {
						isValid: true,
						errorMessage: ''
					};
				} else {
					return {
						isValid: false,
						errorMessage: '账号不符合格式要求，必须是4-16位且包含字母'
					};
				}
			},
			login() {
				// 数据校验 problem_type user_mail
				// const nickNameValidationResult = this.isValidNickName(this.form.nickName);
				// if (!nickNameValidationResult.isValid) {
				// 	return this.$util.toast(nickNameValidationResult.errorMessage);
				// }
				if (this.$validate.isNull(this.form.user_mail)) {
					return this.$util.toast('请输入邮箱');
				}
				if (this.$validate.isNull(this.form.nickName)) {
					return this.$util.toast('请输入账号');
				}
				if (this.$validate.isNull(this.form.user_psw)) {
					return this.$util.toast('请输入登录密码')
				}
				if (this.agree.length === 0) {
					uni.showToast({
						title: '请先同意协议',
						icon: 'none',
						duration: 2000,
					});
					return;
				}
				// 跳转首页

				const newDataObj = {
					user_mail: this.form.user_mail,
					nickName: this.form.nickName,
					user_psw: this.form.user_psw,
					user_sex: 1
				};
				const newDataJsonStr = JSON.stringify(newDataObj);

				const requestData = {
					"processorId": '1008',
					"jobDispatchId": '1',
					"actionId": '7',
					"newData": newDataJsonStr
				};
				const requestDataJsonStr = JSON.stringify(requestData);
				uni.request({
					url: 'http://chat.zwsmcn.com:8090/rest_post',
					header: {
						'content-type': 'application/json'
					},
					data: requestDataJsonStr,
					method: 'POST',
					success: res => {
						const parsedData = JSON.parse(res.data.returnValue);
						console.log(parsedData.new_uid, "-=-=-=-=-=-00000");
						if (parsedData.new_uid == 0) {
							this.$util.toast('账号已经被注册');
							return; // 提前终止，避免执行后续逻辑
						}
						// 提取用户邮箱
						const userId = parsedData.user_mail;
						// console.log(userId, "-=-=-=0-000000")
						let code = res.data.success
						console.log(code);
						this.$util.toast('注册成功')

						uni.navigateBack();

					},
					fail: res => {
						console.log(res);
					}
				});
			},
			oneye() {
				this.passwordShow = false
				this.eyeShow = false
			},
			oneyeOpen() {
				this.passwordShow = true
				this.eyeShow = true
			},
			oneye1() {
				this.passwordShow1 = false
				this.eyeShow1 = false
			},
			oneyeOpen1() {
				this.passwordShow1 = true
				this.eyeShow1 = true
			},
		}
	}
</script>

<style lang="scss" scoped>
	.names {
		width: 100%;
		text-indent: 50px;
		height: 40px;
		line-height: 40px;
	}

	.status_bar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 50upx;
	}



	page {
		background: #f0f0f0;
	}

	.tip {
		width: 100%;
		text-align: center;
		padding: 0 30upx;
		position: absolute;
		bottom: 30upx;

		.item {
			color: #777;
			font-size: 24upx;
			margin-top: 10upx;

			.link {
				color: blue;
				font-size: 24upx;
			}
		}
	}

	.input {
		margin-top: 0 !important;
		margin-bottom: 10px !important;
	}

	.login {
		color: #fff;
		// opacity: 0.6;
		margin: 40upx 100upx;
		padding: 20upx 0;
		text-align: center;
		border-radius: 10upx;
		background: #d54827;

		&.able {
			opacity: 1;
			background-color: #4CD964;
		}
	}

	.logo-wrap {
		margin-top: 10%;
		margin-left: 40%;
		margin-bottom: 30px;

		image {
			width: 180upx;
			height: 180upx;
			border-radius: 50%;

		}
	}

	.input-wrap {
		margin-left: -60upx;
	}

	.input {
		height: 80upx;
		padding: 0 20upx;
		margin: 60upx 100upx 0;
		background: #fafbfd;
		border-radius: 12upx;
		//border: 2upx solid #999;
		margin-left: 160upx;
	}

	.register-btn {
		width: 100%;
		text-align: center;
		color: #d54827;
		font-weight: 300;
		margin-top: -60upx;
	}

	.roule-text {
		color: #cb6781;
		font-weight: 300;
		font-size: 28upx;
	}

	.input-wrap1 {
		margin-left: -60upx;
		position: relative;

		image {
			margin-right: 10upx;
			width: 45upx;
			height: 32upx;
			position: absolute;
			top: 30%;
			right: 13%;
		}
	}
</style>